added some development tools
[windows-sources.git] / developer / Samples / NET Standard / ParallelExtensionsExtras / Drawing / FastBitmap.cs
blob02037fec99687f691f8c8fbd569a58385f853baf
1 //--------------------------------------------------------------------------
2 //
3 // Copyright (c) Microsoft Corporation. All rights reserved.
4 //
5 // File: FastBitmap.cs
6 //
7 //--------------------------------------------------------------------------
9 using System;
10 using System.Drawing;
11 using System.Drawing.Imaging;
13 namespace Microsoft.Drawing
15 public struct PixelData
17 public byte B;
18 public byte G;
19 public byte R;
22 public unsafe class FastBitmap : IDisposable
24 private Bitmap _bitmap;
25 private int _width;
26 private BitmapData _bitmapData = null;
27 private byte* _pBase = null;
28 private PixelData* _pInitPixel = null;
29 private Point _size;
30 private bool _locked = false;
32 public FastBitmap(Bitmap bmp)
34 if (bmp == null) throw new ArgumentNullException("bitmap");
36 _bitmap = bmp;
37 _size = new Point(bmp.Width, bmp.Height);
39 LockBitmap();
42 public PixelData* GetInitialPixelForRow(int rowNumber)
44 return (PixelData*)(_pBase + rowNumber * _width);
47 public PixelData* this[int x, int y]
49 get { return (PixelData*)(_pBase + y * _width + x * sizeof(PixelData)); }
52 public Color GetColor(int x, int y)
54 PixelData* data = this[x, y];
55 return Color.FromArgb(data->R, data->G, data->B);
58 public void SetColor(int x, int y, Color c)
60 PixelData* data = this[x, y];
61 data->R = c.R;
62 data->G = c.G;
63 data->B = c.B;
66 private void LockBitmap()
68 if (_locked) throw new InvalidOperationException("Already locked");
70 Rectangle bounds = new Rectangle(0, 0, _bitmap.Width, _bitmap.Height);
72 // Figure out the number of bytes in a row. This is rounded up to be a multiple
73 // of 4 bytes, since a scan line in an image must always be a multiple of 4 bytes
74 // in length.
75 _width = bounds.Width * sizeof(PixelData);
76 if (_width % 4 != 0) _width = 4 * (_width / 4 + 1);
78 _bitmapData = _bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
80 _pBase = (byte*)_bitmapData.Scan0.ToPointer();
81 _locked = true;
84 private void InitCurrentPixel()
86 _pInitPixel = (PixelData*)_pBase;
89 private void UnlockBitmap()
91 if (!_locked) throw new InvalidOperationException("Not currently locked");
93 _bitmap.UnlockBits(_bitmapData);
94 _bitmapData = null;
95 _pBase = null;
96 _locked = false;
99 public void Dispose()
101 if (_locked) UnlockBitmap();